package com.zang.im.croom.netty;

import com.zang.im.croom.model.dto.WSMessage;
import com.zang.im.croom.netty.common.SSGlobalConstMap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * @author Zhang Qiang
 * @Date 2019/7/23 16:55
 */
@Service
public class EchoServer {

    @Value("${server.port}")
    private int port;
    @Value("${server.address}")
    private String host;
    private EventLoopGroup bossGroup = new NioEventLoopGroup();
    private EventLoopGroup workGroup = new NioEventLoopGroup();
    private ServerBootstrap bootstrap = new ServerBootstrap();

    @Autowired
    private ServerSocketChannelInit channelInitConfig;

    @PostConstruct
    public void run(){
        server();
    }

    @Async("asyncServiceExecutor")
    public void server(){
        try {
        bootstrap.group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .option(ChannelOption.SO_BACKLOG, 1024)
                //发送和接收缓冲大小
                .option(ChannelOption.SO_SNDBUF, 32*1024)
                .option(ChannelOption.SO_RCVBUF, 32*1024)
                //保持长连接
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(channelInitConfig);

            ChannelFuture future = bootstrap.bind(host, port).sync();

            if (future.isSuccess()){
                System.out.println("启动 EchoServer 成功");
            }

            // 等待服务监听端口关闭
            future.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }


     /**
      * 销毁
      */
    @PreDestroy
    public void destroy(){
        bossGroup.shutdownGracefully();
        workGroup.shutdownGracefully();
        System.out.println("关闭 EchoServer");
    }


    public boolean sendMsg(WSMessage wsMsg){

        Channel channel = SSGlobalConstMap.getChannelMap().get(WSMessage.getMsgKey(wsMsg.getMsgId()));

        if (channel == null){
            return true;
        }
        return channel.writeAndFlush(wsMsg).isSuccess();
    }



}
